from flask import Blueprint,jsonify,request
from conf.comm import sqlalchemy_context
from database import *
import json
#实例化
bp_course = Blueprint('course',__name__)

#无限级分类构造
def xtree(data):
    if data:
        #有数据[{'id':1,'son':[{'id':3,'son':[{},{}]},{}]},{},{}]
        list = []
        tree = {}
        for i in data:
            #id做为key,i做为值放到字典中
            tree[i['id']] = i

        #{'1':{'id':1,'name':'34324'},'2':{},}
        for j in data:
            #判断是否有父id，如果没有直接加入list
            if not j['parent']:
                list.append(j)
            else:
                #有父id
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son']=[]
                tree[j['parent']]['son'].append(j)
        return list
    else:
        return data

#添加分类
@bp_course.route('/cateM',methods=['POST','GET'])
@sqlalchemy_context()
def cateM():
    if request.method == "POST":
        # try:
            #获取用户输入
            data = request.data
            if data:
                data = json.loads(data)
            else:
                data = request.form
            #构造对象
            
            try:
                 params = data['params']
            except:
                params = ''
               
            cate = Cate(name=data['name'],parent=data['parent'],level=data['level'],params=params)
            #添加
            db.session.add(cate)
            #提交
            db.session.commit()
            #返回结果
            return jsonify({'code':200})
        # except:
        #     return jsonify({'code':10010})
    else:
        cates = Cate.query.all()
        #定义空列表
        list=[]
        if cates:
            for i in cates:
                dict={'id':i.id,'name':i.name,'level':i.level,'parent':i.parent,'params':i.params}
                list.append(dict)
        #调用xtree方法重构数据
        list1 = xtree(list)
        return jsonify({"code":200,'list':list1})

@bp_course.route('/getCateById')
def getCateById():
    id = request.args.get('id')
    cate = Cate.query.filter_by(id=id).first()
    return jsonify({"code":200,'params':cate.params})


@bp_course.route('/courseM',methods=['POST'])
def courseM():
    data = json.loads(request.data)
    course = Course(title=data['title'],content=data['content'],cid=data['cid'],params=data['params'])
    db.session.add(course)
    db.session.commit()
    return 'ok'
